<template>
  <div class="visitor">
    <a-card>
      <template #title>
        <a-form layout="inline" :model="formState" @finish="onSearch">
          <a-form-item :style="{ width: '18.75rem' }">
            <a-input v-model:value="formState.search" placeholder="输入姓名">
            </a-input>
          </a-form-item>
          <a-form-item v-if="authority === 'ROLE_admin'" :style="{ width: '18.75rem' }">
            <a-select
              v-model:value="formState.buildId"
              placeholder="请选择楼栋"
            >
             <a-select-option value="">请选择楼栋</a-select-option>
              <a-select-option v-for="item in buildData" :key="item.id" :value="item.id">{{
                item.name
              }}</a-select-option>
            </a-select>
          </a-form-item>
          <!-- <a-form-item :style="{ width: '18.75rem' }">
            <a-select
              v-model:value="formState.type"
              placeholder="请选择宿舍类型"
            >
             <a-select-option value="">全部宿舍</a-select-option>
            <a-select-option value="女生宿舍">女生宿舍</a-select-option>
            <a-select-option value="男生宿舍">男生宿舍</a-select-option>
            </a-select>
          </a-form-item> -->

          <a-form-item>
            <a-button type="primary" shape="circle" html-type="submit">
              <template #icon><SearchOutlined /></template>
            </a-button>
            <a-button shape="circle" style="margin-left: 8rpx" @click="onRest">
              <template #icon><CloseCircleOutlined /></template>
            </a-button>
          </a-form-item>
        </a-form>
      </template>
       <template #extra>
        <a-button type="primary" @click="onEdit('add')">添加</a-button>
      </template>
      <a-table
        row-key="id"
        :columns="dataColumns"
        :loading="loading"
        :data-source="dataSource"
        bordered
        :pagination="pagination"
        @change="onChange"
      >

        <template #operation="{ record }">
          <div class="operation-box">
            <a-button type="primary" @click="onEdit('update', record)"
              >修改</a-button
            >
            <a-button @click="onEdit('del', record)">删除</a-button>
          </div>
        </template>
      </a-table>
    </a-card>
    <a-modal
      v-model:visible="visible"
      :title="title"
      :destroyOnClose="true"
      :footer="null"
    >
      <template v-if="option !== 'del'">
        <a-form
          ref="FormRef"
          :rules="Rules"
          :model="Form"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
        >
          <a-form-item v-show="false" label="id" ref="id" name="id">
            <a-input v-model:value="Form.adminId" />
          </a-form-item>

          <a-form-item  label="姓名" ref="name" name="name">
            <a-input v-model:value="Form.name" />
          </a-form-item>
          <a-form-item  label="手机号" ref="phone" name="phone">
            <a-input v-model:value="Form.phone" />
          </a-form-item>
           <a-form-item  v-if="authority === 'ROLE_admin'" label="楼栋" ref="buildId" name="buildId" >
            <a-select
              v-model:value="Form.buildId"
              placeholder="请选择楼栋"
            >
              <a-select-option v-for="item in buildData" :key="item.id" :value="item.id+''">{{
                item.name
              }}</a-select-option>
            </a-select>
          </a-form-item>

           <a-form-item label="状态" ref="sex" name="sex">
           <a-radio-group v-model:value="Form.sex">
              <a-radio value="男">男</a-radio>
              <a-radio value="女">女</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item  label="备注" ref="remark" name="remark">
           <a-textarea v-model:value="Form.remark" :rows="4" />
          </a-form-item>

          <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
            <a-button type="primary" @click="onSubmit">提交</a-button>
          </a-form-item>
        </a-form>
      </template>
      <template v-else>
        <div class="del-modal" style="text-align: center">
          <p>是否删除{{Form.name}}到访信息？</p>
          <a-button type="primary" @click="onDel">删除</a-button>
        </div>
      </template>
    </a-modal>
  </div>
</template>
<script lang="ts">
import { computed, defineComponent, reactive, ref, UnwrapRef } from 'vue'
import { TableState } from 'ant-design-vue/es/table/interface'
import {
  visitorList,
  buildingNameList,
  addVisitor,
  delVisitor,
  updateVisitor,
  handleRepair
} from '@/api'
import { message } from 'ant-design-vue'
import { useStore } from 'vuex'
type Pagination = TableState['pagination'];
interface FormState {
  search: string | null;
  buildId: string | null;
}

interface IForm {
  id: string;
  buildId: string;
  name:string;
  sex:string;
  remark:string;
  phone:string;
}
const dataColumns = [
  {
    title: 'ID',
    dataIndex: 'id'
  },
  {
    title: '姓名',
    dataIndex: 'name'
  },
  {
    title: '性别',
    dataIndex: 'sex'
  },
  {
    title: '手机号',
    dataIndex: 'phone'
  },
  {
    title: '宿舍ID',
    dataIndex: 'buildingId'
  },
  {
    title: '宿舍楼名称',
    dataIndex: 'buiName',
    customRender: (e: any) => {
      const { text } = e
      return text ?? '--'
    }
  },
  {
    title: '宿舍类别',
    dataIndex: 'type',
    customRender: (e: any) => {
      const { text } = e
      return text ?? '--'
    }
  },
  {
    title: '备注',
    dataIndex: 'remark'
  },

  {
    title: '创建时间',
    dataIndex: 'createTime'
  },

  {
    title: '操作',
    width: '280px',
    dataIndex: 'operation',
    slots: { customRender: 'operation' }
  }
]

export default defineComponent({
  setup () {
    const store = useStore()
    const FormRef = ref()
    const labelCol = store.state.labelCol
    const wrapperCol = store.state.wrapperCol
    const Form: UnwrapRef<IForm> = reactive({
      id: '',
      buildId: '',
      name: '',
      sex: '',
      remark: '',
      phone: ''
    })
    const Rules = {
      buildId: [{ required: true, message: '请选择宿舍楼', trigger: 'blur' }],
      name: [{ required: true, message: '请输入名称', trigger: 'change' }],
      sex: [{ required: true, message: '请选择性别', trigger: 'blur' }],
      remark: [{ required: true, message: '请输入备注', trigger: 'blur' }],
      phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }, {
        pattern: /(^((0\d{2,3}-\d{7,8})|(1[3456789]\d{9}))$)|(^(1[3456789]\d{9})$)/,
        message: '请输入正确的手机号',
        trigger: 'blur'
      }]
    }

    const formState: UnwrapRef<FormState> = reactive({
      search: '',
      buildId: '',
      type: ''
    })
    const buildData = ref([])
    const buildingNameListFunc = async () => {
      const {
        data: { obj, status }
      } = await buildingNameList()
      if (status === 200) {
        buildData.value = obj
      }
    }
    const authority = computed(() => store.state.authModule.userInfo?.authorities[0]?.authority)
    if (authority.value === 'ROLE_admin') {
      buildingNameListFunc()
    }

    const dataSource = ref([])
    const loading = ref(false)
    const loadingBtn = ref(false)
    // 分页
    const pagination: Pagination = reactive({
      total: 0,
      current: 1,
      pageSize: 5,
      showSizeChanger: true
    })
    const visitorListFunc = async () => {
      loading.value = true
      const {
        data: { data, total }
      } = await visitorList({
        pageNum: pagination.current,
        pageSize: pagination.pageSize,
        keywords: formState.search,
        buildId: formState.buildId
      })

      pagination.total = total
      dataSource.value = data
      loading.value = false
    }
    visitorListFunc()
    const onSearch = () => {
      loading.value = true
      updateListFunc(1)
    }
    const onRest = () => {
      loading.value = true
      formState.search = ''
      formState.buildId = ''
      updateListFunc(1)
    }
    const onChange = (pag: Pagination) => {
      // filters:TableStateFilters, sorter:any, data:any
      loading.value = true
      pagination.pageSize = pag?.pageSize
      updateListFunc(pag?.current)
    }
    // 模态框
    const onSubmit = () => {
      FormRef.value.validate().then(async () => {
        const values = {
          buildingId: Form.buildId,
          name: Form.name,
          remark: Form.remark,
          phone: Form.phone,
          id: '',
          sex: Form.sex
        }
        if (Form.id) {
          values.id = Form.id
        }
        if (option.value === 'update') {
          updateVisitor(values).then((res) => {
            const {
              data: { status, msg }
            } = res
            if (status === 200) {
              message.success(msg)
            }
          })
        } else {
          const { data: { status, msg } } = await addVisitor(values)
          if (status === 200) {
            message.success(msg)
          }
        }
        visible.value = false
        for (const key in Form) {
          Form[key as keyof IForm] = ''
        }
        loading.value = true
        updateListFunc(1)
      })
    }
    const visible = ref(false)
    const option = ref('')
    const title = ref('')
    const name = ref('')
    const onEdit = async (options: string, obj: any) => {
      visible.value = true
      if (obj) {
        Form.id = obj.id
        Form.buildId = obj.buildingId + ''
        Form.name = obj.name
        Form.phone = obj.phone
        Form.remark = obj.remark
        Form.sex = obj.sex
      }
      if (options === 'update') {
        title.value = '修改访客信息'
        option.value = 'update'
      } else if (options === 'del') {
        title.value = '删除访客信息'
        name.value = obj.building_name
        option.value = 'del'
      } else if (options === 'add') {
        for (const key in Form) {
          Form[key as keyof IForm] = ''
        }
        title.value = '添加访客信息'
        option.value = 'add'
      }
    }
    const onDel = () => {
      delVisitor(Form.id).then((res) => {
        reqestSuccessFunc(res)
      })
    }
    const onHandle = (id:string) => {
      handleRepair({ id, enabled: true }).then(res => {
        reqestSuccessFunc(res)
      })
    }
    const reqestSuccessFunc = (res:any) => {
      const {
        data: { status, msg }
      } = res
      if (status === 200) {
        message.success(msg)
        visible.value = false
        updateListFunc(1)
      }
    }

    const updateListFunc = (current: number | undefined) => {
      /***
       * 更新列表
       */
      pagination.current = current
      visitorListFunc()
    }
    return {
      dataSource,
      dataColumns,
      pagination,
      loading,
      loadingBtn,
      formState,
      buildData,
      visible,
      title,
      Form,
      option,
      wrapperCol,
      Rules,
      FormRef,
      labelCol,
      name,
      authority,
      onSubmit,
      onSearch,
      onRest,
      onChange,
      onEdit,
      onDel,
      onHandle
    }
  }
})
</script>
<style lang="less" scoped>

</style>
